package com.gec.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gec.model.entity.SysCountRole;
import com.gec.model.entity.SysRole;
import com.gec.model.vo.AssginRoleVo;
import com.gec.model.vo.SysRoleQueryVo;
import com.gec.system.mapper.SysCountRoleMapper;
import com.gec.system.mapper.SysRoleMapper;
import com.gec.system.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author Liangxj
 * @since 2023-12-06
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysCountRoleMapper sysCountRoleMapper;

    @Override
    public IPage<SysRole> selectPage(IPage<SysRole> page1, SysRoleQueryVo sysRoleQueryVo) {
        IPage<SysRole> iPage =  this.baseMapper.selectPage(page1,sysRoleQueryVo);
        return iPage;
    }

    @Override
    public Map<String, Object> getRolesByCountId(Long userId) {
        Map<String,Object>map = new HashMap<>();
        //获得全部角色列表
        List<SysRole> allRoles = this.baseMapper.selectList(null);


        //获得当前用户角色信息
        List<Long> roleIds = new ArrayList<>();
        QueryWrapper<SysCountRole>wrapper = new QueryWrapper<>();
        wrapper.eq("count_id",userId);
        List<SysCountRole> roles = sysCountRoleMapper.selectList(wrapper);
        roles.forEach(role->{
            roleIds.add(role.getRoleId());
        });
        //装载数据
        map.put("allRoles",allRoles);
        map.put("roleIds",roleIds);

        return map;
    }

    //给用户分配角色信息
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {

        //1、先要删除原有的该用户角色信息
        QueryWrapper<SysCountRole> wrapper = new QueryWrapper<>();
        wrapper.eq("count_id",assginRoleVo.getCountId());
        this.sysCountRoleMapper.delete(wrapper);
        Long countId = assginRoleVo.getCountId();
        //2、给用户分配新的id，也就是添加用户角色信息
        //获取所有角色id
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        if (roleIdList!=null){
            roleIdList.forEach(roleId->{
                if (roleId!=null){
                    SysCountRole sysCountRole = new SysCountRole();
                    sysCountRole.setRoleId(roleId);
                    sysCountRole.setCountId(countId);
                    //保存
                    this.sysCountRoleMapper.insert(sysCountRole);
                }
            });
        }


    }

}
